package com.sky.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        Result errorResult = Result.error("未登录");

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());

        if (token == null){
            log.info("校验失败：未获取到令牌");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            sendJsonError(response, HttpServletResponse.SC_UNAUTHORIZED, errorResult);
            return false;
        }

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前用户id：{}", userId);
            //设置当前登录用户id
            Long id = BaseContext.setCurrentId(userId);
            //3、通过，放行
            log.info("校验通过");
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            log.info("校验失败：{}", ex.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
//        finally {
//            log.info("校验完成");
//            BaseContext.removeCurrentId();
//        }
    }

    /**
     * 发送JSON格式的错误响应
     */
    private void sendJsonError(HttpServletResponse response, int status, Result result) throws Exception {
        response.setStatus(status);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(JSONObject.toJSONString(result));
        out.flush();
        out.close();
    }
}
